package org.gracefulwebsocket;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

/**
 * A more advanced chat service that supports both push and poll for messages.
 * 
 * Message polling is implemented using a custom poll parameter: latestMessageID (timestamp). 
 * Server returns all new messages since previously fetched message
 * 
 * @author david.lindkvist
 *
 */
public class SmartChatServiceServlet extends ChatServiceServlet implements Servlet 
{
	private static final long serialVersionUID = 2010031501L;
	
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
	{
		long latestMessage = getRequestTimestamp(req, "latestMessageID");
		
		if(latestMessage < 0)
			latestMessage = getRequestTimestamp(req, "currentRequest");	
		
		res.setContentType("text/html;charset=utf-8");
		res.getWriter().write( getMessagesAsJSON(latestMessage) );
	}
	
	protected String getMessagesAsJSON(long latestMessage) 
	{
		JSONArray msgs = new JSONArray();
		for(ChatMessage msg : echoBufferFIFO)
		{
			if(msg.timestamp > latestMessage)
				msgs.put(msg.toJSONObject());
		}
		return msgs.toString();
	}
	
}